use derive_builder::Builder;
use serde::{Deserialize, Serialize};

use super::{
    Class, ClassAttribute, ClassAttributeBuilder, ClassBuilder, ClassGetter, ClassRelation,
    ClassRelationBuilder, Domain, RelationRelatedType,
};
use crate::error::Error;
use crate::mapper::ValueMapper;
use crate::modeling::{
    ClassAttributePersistence, ClassPersistence, ClassPersistenceBuilder, ClassPersistenceGetter,
    ClassRelationGetter, Value, ValueType,
};

const RELATION_CLASS_IDENTIFIER: &'static str = "g01_relation";

const RELATION_CLASS_NAME: &'static str = "relation";

const RELATION_TABLE_NAME: &'static str = "_g01_meta_relations";

#[derive(Debug, Default, Serialize, Deserialize, Clone, PartialEq)]
pub enum RelationType {
    /// 继承
    #[serde(rename = "inherit")]
    Inherit,
    #[default]
    /// 组成  拥有
    #[serde(rename = "composition")]
    Composition,
    /// 聚合
    #[serde(rename = "aggregation")]
    Aggregation,
    /// 使用
    #[serde(rename = "use")]
    Use,
    /// 影响
    #[serde(rename = "impact")]
    Impact,
    /// 依赖
    #[serde(rename = "dependent")]
    Dependent,
}

#[derive(Debug, Default, Serialize, Deserialize, Clone, PartialEq)]
pub enum RelationMappingType {
    OneToOne,
    #[default]
    StrictOneToOne,
    /// 一对多[0,-]
    OneToMany,
    /// 一对多[1,-]
    StrictOneToMany,
    /// 多对多
    ManyToMany,
    StrictManyToMany,
    /// 多对一
    ManyToOne,
    StrictManyToOne,
}

#[derive(Debug, Serialize, Deserialize, Default, Clone, Builder, PartialEq)]
#[builder(name = "RelationBuilder")]
#[builder(pattern = "mutable")]
#[builder(setter(into, strip_option), default)]
#[builder(derive(Debug))]
#[builder(build_fn(error = "Error"))]
pub struct Relation {
    /// id
    pub id: i64,
    /// domain identity
    pub domain_identifier: String,
    /// identifier
    pub identifier: String,
    /// 名称
    pub name: String,
    /// 名称
    pub title: String,
    /// 图标
    pub icon: Option<String>,
    /// 类型
    pub relation_type: RelationType,
    /// 是否泛化
    pub is_generalization: bool,
    /// 注释
    pub comments: Option<String>,
    /// 选项
    pub options: Option<String>,
    /// 备注
    pub description: String,
    /// 创建时间
    pub created_at: i64,
    /// 更新时间
    pub updated_at: i64,
}

impl ValueMapper for Relation {}
//
crate::impl_from_value!(Relation);
crate::impl_class_persistence_getter!(Relation, RELATION_TABLE_NAME);
crate::impl_class_relations_getter!(
    Relation,
    vec![ClassRelationBuilder::default()
        .src_identifier(Domain::get_identifier()?)
        .target_identifier(Self::get_identifier()?)
        .related_type(RelationRelatedType::Keys)
        .related_at("domain_identifier")
        .build()?]
);

impl ClassGetter for Relation {
    fn get_name() -> anyhow::Result<String> {
        Ok(String::from(RELATION_CLASS_NAME))
    }

    fn get_identifier() -> anyhow::Result<String> {
        Ok(String::from(RELATION_CLASS_IDENTIFIER))
    }
    fn get_class() -> anyhow::Result<Class> {
        let mut attribute_builder = ClassAttributeBuilder::default();
        attribute_builder.class_identifier(RELATION_CLASS_IDENTIFIER);

        let mut commons = super::common_attributes_with_builder(&attribute_builder)?;
        let mut append = vec![
            attribute_builder
                .clone()
                .name("domain_identifier")
                .title("领域")
                .data_type(ValueType::String)
                .build()?,
            attribute_builder
                .clone()
                .name("relation_type")
                .title("类型")
                .data_type(ValueType::String)
                .build()?,
            attribute_builder
                .clone()
                .name("is_generalization")
                .title("是否泛化")
                .data_type(ValueType::Boolean)
                .build()?,
        ];
        append.append(&mut commons);
        append.sort_by(|a, b| a.position.cmp(&b.position));
        let clazz = ClassBuilder::default()
            .identifier(RELATION_CLASS_IDENTIFIER)
            .name(RELATION_CLASS_NAME)
            .data_is_type(false)
            .is_persistent(true)
            .primary_key(String::from("identifier"))
            .attributes(append)
            .build()?;
        Ok(clazz)
    }
}
